home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 12484 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  63 lines

  1. Path: news.mcs.net!not-for-mail
  2. From: supercat@MCS.COM (John Payson)
  3. Newsgroups: comp.arch.embedded,comp.lang.c
  4. Subject: Re: Using malloc of C on embedded system?
  5. Date: 1 Apr 1996 00:52:38 -0600
  6. Organization: /usr/lib/news/organi[sz]ation
  7. Message-ID: <4jnufm$lr1@Mercury.mcs.com>
  8. References: <4jml7h$cbc@castor.usc.edu>
  9. NNTP-Posting-Host: mercury.mcs.com
  10.  
  11. In article <4jml7h$cbc@castor.usc.edu>,
  12. Stannon Yen <chuitiny@castor.usc.edu> wrote:
  13. >Hello,
  14. >
  15. >   This is just a general question. Is it possible to use C function
  16. >malloc and free on system that has no OS? How can I setup the memory
  17. >pool for dynamic allocation/deallocation of memory?
  18. >
  19. >   Any help is welcome.
  20.  
  21. If your C library does not already provide a malloc/free function pair, your
  22. best bet is probably to declare an array which uses up all available memory,
  23. and then allocate stuff out of that.
  24.  
  25. As to how complex you make your malloc/free functions, that depends in
  26. large measure upon what you need to do with them.  For example, one really
  27. easy approach is:
  28.  
  29. static char memory_data[MEM_SIZE];
  30. static char *mem_end;
  31.  
  32. void initmem(void)
  33. {
  34.   mem_end = memory_data;
  35. }
  36.  
  37. void *malloc(int size)
  38. {
  39.   char *temp = mem_end;
  40.   mem_end += size;
  41.   return (void*) temp;
  42. }
  43.  
  44. void free(void *ptr)
  45. {
  46.   /* Don't bother to free anything--if programs need to start over, they
  47.      can re-invoke initmem */
  48. }
  49.  
  50. As you can see, this approach is very easy and--in many embedded systems--
  51. quite adequate.  If it's important that "free" actually DOES something,
  52. you should consider carefully the what size pieces you'll be malloc'ing
  53. and free'ing and what this could do to memory fragmentation.  If the sizes
  54. of the things you'll be allocating tend to be powers of two, I'd highly
  55. suggest looking at a "binary buddy" system; they require little overhead,
  56. offer O(lg(n)) alloc/release, and tend to be relatively immune to external
  57. fragmentation.
  58.  
  59. -- 
  60. -------------------------------------------------------------------------------
  61.  supercat@mcs.com    |  "Je crois que je ne vais jamais voir...  |   J\_/L
  62.  John Payson         |   Un animal aussi beau qu'un chat."       |  ( o o )
  63.